package com.lindroy.lib_utils.statics


import android.content.Context
import android.os.Environment
import java.io.File
import java.math.BigDecimal

/**
 * @author Lin
 * @date 2022/3/1
 * @function 缓存工具类
 */


object CacheUtil {

    private var cacheClearListener: OnCacheClearListener? = null

    /**
     * 获取当前的缓存
     */
    fun getTotalCacheSize(context: Context): String {
        var cacheSize = getFileSize(context.cacheDir)
        //有SD卡
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            context.externalCacheDir?.also {
                cacheSize += getFileSize(it)
            }
        }
        return formatSize(cacheSize = cacheSize.toDouble())
    }

    /**
     * 清除所有缓存
     */
    fun clearAllCache(context: Context, cacheClearListener: OnCacheClearListener? = null) {
        cacheClearListener?.also {
            setOnCacheClearListener(it)
        }
        deleteDir(context.cacheDir)
        //有SD卡
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            deleteDir(context.externalCacheDir)
        }

    }


    /**
     * 获取文件或文件夹大小
     */
    fun getFileSize(file: File): Long {
        var size = 0L
        try {
            val fileList = file.listFiles()
            if (fileList != null) {
                for (fileBean in fileList) {
                    //如果是一个文件夹，则递归
                    size = when (fileBean.isDirectory) {
                        true -> size.plus(getFileSize(fileBean))
                        false -> size + fileBean.length()
                    }

                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return size
    }

    /**
     * 删除文件，删除成功则返回true
     */
    fun deleteDir(dir: File?): Boolean {
        return when {
            dir != null && dir.isDirectory -> {
                var isSuccess = true
                val childList = dir.list()
                if (childList != null) {
                    for (child in childList) {
                        //只要有一个删除不了就返回false
                        if (!deleteDir(File(dir, child))) {
                            isSuccess = false
                            break
                        }
                    }
                }
                cacheClearListener?.onFinish(isSuccess)
                isSuccess
            }
            dir == null -> {
                cacheClearListener?.onFinish(true)
                true
            }
            else -> {
                val isSuccess = dir.delete()
                cacheClearListener?.onFinish(isSuccess)
                isSuccess

            }
        }
    }

    private fun setOnCacheClearListener(cacheClearListener: OnCacheClearListener) {
        this.cacheClearListener = cacheClearListener
        this.cacheClearListener?.onStart()
    }


    fun formatSize(cacheSize: Double): String {
        val kiloByte = cacheSize / 1024
        if (kiloByte < 1) {
            return "${cacheSize}B"
        }
        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result = BigDecimal(kiloByte)
            //保留两位小数，并四舍五入
            return "${result.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()}KB"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result = BigDecimal(megaByte)
            return "${result.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()}MB"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result = BigDecimal(gigaByte)
            return "${result.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()}GB"
        }
        val result = BigDecimal(teraBytes)
        return "${result.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()}TB"
    }

    interface OnCacheClearListener {
        fun onStart()

        fun onFinish(success: Boolean)
    }

}